package com.ant.storage.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ant.storage.common.ResultCode;
import com.ant.storage.dto.UserInfoDto;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.UserCityMapper;
import com.ant.storage.mapper.UserInfoMapper;
import com.ant.storage.pojo.Dictionary;
import com.ant.storage.pojo.*;
import com.ant.storage.service.*;
import com.ant.storage.vo.CityVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author melon
 * @since 2023-07-17
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Value("${loginUrl.url}")
    private String Url;

    @Autowired
    private IWarehouseService warehouseService;

    @Autowired
    private IDictionaryService dictionaryService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private ISupplierInformationService supplierInformationService;
    @Resource
    private UserCityMapper userCityMapper;
    // 在需要使用上下文的地方直接注入，前提，被spring管理
    @Autowired
    public ServletContext servletContext;

    @Autowired
    IUserRoleService userRoleService;

    @Override
    public PageInfo<UserInfo> getUserInfoPage(UserInfoDto dto) {
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        // 先写条件
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getUsername())) {
            wrapper.like("user_name", dto.getUsername());
        }
        if (StringUtils.isNotEmpty(dto.getTel())) {
            wrapper.like("tel", dto.getTel());
        }
        if (StringUtils.isNotEmpty(dto.getCityId())) {
            wrapper.eq("city_id", dto.getCityId());
        }
        if (dto.getCustom()!= null ) {
            wrapper.eq("custom", dto.getCustom());
        }
        wrapper.orderByAsc("id");
        List<UserInfo> infoList = this.baseMapper.selectList(wrapper);
        infoList.stream().map(item -> {
            List<UserCity> user_id = userCityMapper.selectList(new QueryWrapper<UserCity>()
                    .eq("user_id", item.getId()));
            item.setCityPermissionList(user_id.stream().map(UserCity::getCityId).collect(Collectors.toList()));
            List<UserRole> user_role = userRoleService.list(new QueryWrapper<UserRole>()
                    .eq("user_id", item.getId()));
            item.setRoleList(user_role.stream().map(UserRole::getRoleId).collect(Collectors.toList()));
            return item;
        }).collect(Collectors.toList());
        PageInfo<UserInfo> pageInfo = new PageInfo<>(infoList);
        return pageInfo;
    }


    @Override
    public void userInfoUpdate(UserInfo userInfo) {
        this.baseMapper.updateById(userInfo);
        UserCity city=new UserCity();
        city.setUserId(userInfo.getId());
        userCityMapper.delete(new QueryWrapper<UserCity>().eq("user_id", userInfo.getId()));
        userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", userInfo.getId()));
        if (userInfo.getRoleList() != null && userInfo.getRoleList().size() != 0) {
            userInfo.getRoleList().forEach(id -> {
                UserRole userRole = new UserRole();
                userRole.setUserId(userInfo.getId());
                userRole.setRoleId(id);
                userRoleService.save(userRole);
            });
        }
        userInfo.getCityPermissionList().forEach(c -> {
            city.setCityId(c);
            userCityMapper.insert(city);
        });
        this.baseMapper.updateById(userInfo);
    }

    @Override
    public UserInfo getUserInfoById(Integer id) {
        if (id == null) {
            throw new AntException(ResultCode.FAILURE.getCode(), "id不能为空");
        }
        UserInfo userInfo = this.baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("id", id));
        List<UserCity> user_id = userCityMapper.selectList(new QueryWrapper<UserCity>().eq("user_id", id));
        userInfo.setCityPermissionList(user_id.stream().map(UserCity::getCityId).collect(Collectors.toList()));
        List<UserRole> user_role = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", id));
        userInfo.setRoleList(user_role.stream().map(UserRole::getRoleId).collect(Collectors.toList()));
        return userInfo;
    }

    @Override
    public UserInfo login(UserInfoDto dto) throws Exception {
        Map<String, Object> param = new HashMap<>();
        if (dto.getLoginType().equals("code")) {
            // 验证码登录
            param.put("tel", dto.getTel());
            param.put("code", dto.getPassword());
        } else {
            // 密码登录
            param.put("tel", dto.getTel());
            param.put("password", dto.getPassword());
        }
        String str = HttpUtil.post(Url + "/userSystem/login/loginByManager", JSONUtil.toJsonStr(param));
        UserInfo userInfo = getUserInfoPc(str);
        if (userInfo != null) {
            userInfo.setCityList(findCityList());
            userInfo.setWarehouseList(findWarehouseList());
            userInfo.setDictionaryList(findDictionaryList());
            userInfo.setDepartmentList(findDepartmentList());
            userInfo.setSupplierList(findSupplierList());
            return userInfo;
        }
        return userInfo;
    }

    /**
     * 职员登录
     *
     * @param dto
     * @return
     * @throws Exception
     */
    @Override
    public UserInfo findLogin(UserInfoDto dto) throws Exception {
        Map<String, Object> param = new HashMap<>();
        if (dto.getLoginType().equals("code")) {
            // 验证码登录
            param.put("tel", dto.getTel());
            param.put("code", dto.getPassword());
        } else {
            // 密码登录
            param.put("tel", dto.getTel());
            param.put("password", dto.getPassword());
        }
        String str = HttpUtil.post(Url + "/userSystem/login/loginByManager", JSONUtil.toJsonStr(param));
        UserInfo userInfo = getUserInfoPc(str);
        if (userInfo != null) {
            //获取城市列表
            userInfo.setCityList(findCityList());
            //获取仓库列表
            userInfo.setWarehouseList(findWarehouseList());
            userInfo.setDictionaryList(findDictionaryList());
            userInfo.setDepartmentList(findDepartmentList());
            userInfo.setSupplierList(findSupplierList());
            return userInfo;
        }
        return null;
    }

    /**
     * 一线登录
     *
     * @param dto
     * @return
     * @throws Exception
     */
    @Override
    public UserInfo aLineOfLogin(UserInfoDto dto) throws Exception {
        Map<String, Object> param = new HashMap<>();
        String str;
        if (dto.getLoginType().equals("code")) {
            // 验证码登录
            param.put("phone", dto.getTel());
            param.put("number", dto.getPassword());
            param.put("code", dto.getCode());
            str = HttpUtil.get(Url + "/userSystem/verify/phoneValidation", param);
        } else {
            // 密码登录
            param.put("telephone", dto.getTel());
            param.put("password", dto.getPassword());
            str = HttpUtil.post( Url + "/userSystem/personnel/aLineOfLogin", JSONUtil.toJsonStr(param));
        }
        UserInfo userInfo = getPersonnel(str);
        if (userInfo!=null) {
            userInfo.setCityList(findCityList());
            userInfo.setWarehouseList(findWarehouseList());
            userInfo.setDictionaryList(findDictionaryList());
            userInfo.setDepartmentList(findDepartmentList());
            userInfo.setSupplierList(findSupplierList());
            return userInfo;
        }
        return null;
    }

    /**
     * 获取职员登录信息
     *
     * @param str
     * @return
     * @throws Exception
     */
    public UserInfo getUserInfoPc(String str) throws Exception {
        JSONObject object = JSONUtil.parseObj(str);
        Integer code = (Integer) object.get("code");
        if (code == 200) {
            String data = object.get("data").toString();
            JSONObject objectData = JSONUtil.parseObj(data);
            String user = objectData.get("user").toString();
            JSONObject object2 = JSONUtil.parseObj(user);
            String userId = object2.get("id").toString();
            String personnel = object2.get("personnel").toString();
            JSONObject personnelObject = JSONUtil.parseObj(personnel);
            JSONArray roleArray = (JSONArray) object2.get("role");
            String role = roleList(roleArray);
            UserInfo one = this.baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("tel",
                    object2.get("tel").toString().trim()));
            UserInfo userInfo = new UserInfo();
            String dingTalk = "";
            String divisive = "1";
            String cityId = "1";
            String weChat ="";

            if (!personnelObject.isNull("dingTalk")) {
                dingTalk = personnelObject.get("dingTalk").toString();
            }
            if (!personnelObject.isNull("divisive")) {
                divisive = personnelObject.get("divisive").toString();
            }
            if (!personnelObject.isNull("cityId")) {
                cityId = personnelObject.get("cityId").toString();
            }
            if (!personnelObject.isNull("weChat")) {
                weChat = personnelObject.get("weChat").toString();
            }

            if (one == null) {
                userInfo.setNameId(Integer.valueOf(userId));
                userInfo.setUserName(object2.get("name").toString());
                userInfo.setTel(object2.get("tel").toString());
                userInfo.setToken(objectData.get("token").toString());
                userInfo.setCreationTime(new Date());
                userInfo.setDingTalk(dingTalk);
                userInfo.setPersonnelId(personnelObject.get("id").toString());
                userInfo.setDivisive(divisive);
                userInfo.setCityId(Integer.valueOf(cityId));
                userInfo.setLastLogin(new Date());
                userInfo.setUserMsg(user);
                userInfo.setWeChat(weChat);
                this.baseMapper.insert(userInfo);
                userInfo.setUserMsg(user);
                userInfo.setRole(role);
                servletContext.setAttribute("userInfo", userInfo);
                return userInfo;
            } else {
                servletContext.setAttribute("userInfo", one);
                UserInfo info = new UserInfo();
                info.setId(one.getId());
                info.setToken(objectData.get("token").toString());
                if (StringUtils.isNotEmpty(divisive)) {
                    info.setDivisive(divisive);
                }
                if (StringUtils.isNotEmpty(dingTalk) || one.getDingTalk() == null || StringUtils.isEmpty(one.getDingTalk())) {
                    info.setDingTalk(dingTalk);
                }
                if (one.getUserMsg() == null) {
                    info.setUserMsg(user);
                }
                info.setPersonnelId(personnelObject.get("id").toString());
                info.setLastLogin(new Date());
                info.setNamesId(Integer.valueOf(userId));
                info.setUserMsg(user);
                if(weChat!=null && !weChat.equals("")){
                    info.setWeChat(weChat);
                }
                this.baseMapper.updateById(info);
                UserInfo userInfo1 = this.baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("id", one.getId()));
                userInfo1.setRole(role);
                return userInfo1;
            }
        } else {
            throw new AntException(ResultCode.FAILURE.getResultCode(), object.get("msg").toString());
        }
    }

    /**
     * 获取一线登录
     *
     * @param str
     * @return
     * @throws Exception
     */
    public UserInfo getPersonnel(String str) throws Exception {
        JSONObject object = JSONUtil.parseObj(str);
        Integer code = (Integer) object.get("code");
        if (code == 200) {
            String data = object.get("data").toString();
            JSONObject objectData = JSONUtil.parseObj(data);
            String name = objectData.get("name").toString();
            String telephone = objectData.get("telephone").toString();
            String cityId = objectData.get("cityId").toString();
            String userId = objectData.get("id").toString();
            String token = objectData.get("token").toString();
            UserInfo one = this.baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("personnel_id",
                    Integer.valueOf(userId)));
            UserInfo userInfo = new UserInfo();
            if (one == null) {
                userInfo.setNameId(Integer.valueOf(userId));
                userInfo.setUserName(name);
                userInfo.setTel(telephone);
                userInfo.setToken(token);
                userInfo.setCityId(Integer.valueOf(cityId));
                userInfo.setPersonnelId(userId);
                userInfo.setDivisive("0");
                userInfo.setCreationTime(new Date());
                userInfo.setRole("procure");
                userInfo.setLastLogin(new Date());
                this.baseMapper.insert(userInfo);
                userInfo.setUserMsg(null);
                servletContext.setAttribute("userInfo", userInfo);
                return userInfo;
            } else {
                one.setToken(token);
                one.setUserMsg(null);
                one.setLastLogin(new Date());
                one.setNamesId(Integer.valueOf(userId));
                this.baseMapper.updateById(one);
                one.setUserMsg(null);
                one.setRole("procure");
                servletContext.setAttribute("userInfo", one);
                return one;
            }
        } else {
            throw new AntException(ResultCode.FAILURE.getResultCode(), object.get("msg").toString());
        }
    }

    @Override
    public String findCode(UserInfoDto dto) {
        Map<String, Object> param = new HashMap<>();
        param.put("tel", dto.getTel());
        param.put("password", dto.getPassword());
        String str = HttpUtil.post(Url + "/userSystem/personnel/aLineOfLogin", JSONUtil.toJsonStr(param));
        return str;
    }

    private String roleList(JSONArray object) {
        ArrayList arrayList = new ArrayList();
        for (int i = 0; i < object.size(); i++) {
            JSONObject jsonObject = object.getJSONObject(i);
            if (jsonObject.getStr("name").contains("超级管理员")) {
                arrayList.add("vadmin");
                servletContext.setAttribute("roles", "vadmin");
                break;
            }
            if (jsonObject.getStr("name").contains("仓库管理员")) {
                arrayList.add("admins");
                break;
            }
            if (jsonObject.getStr("name").contains("采购")) {
                arrayList.add("procure");
            }
            if (jsonObject.getStr("name").contains("车蚂蚁")) {
                arrayList.add("car");
            }
            if (jsonObject.getStr("name").contains("招投标")) {
                arrayList.add("tendering");
            }
            if (jsonObject.getStr("name").contains("库管员")) {
                arrayList.add("warehouse");
            }
            if (jsonObject.getStr("name").contains("财务")) {
                arrayList.add("price");
            }
        }
        if (arrayList.size() == 0) {
            arrayList.add("default");
        }
        if (arrayList.contains("vadmin")) {
            arrayList.clear();
            arrayList.add("vadmin");
            return arrayList.stream().reduce((a, b) -> a + "" + b).orElse("").toString();
        } else if (arrayList.contains("admins")) {
            arrayList.clear();
            arrayList.add("admins");
            return arrayList.stream().reduce((a, b) -> a + "" + b).orElse("").toString();
        } else if (arrayList.contains("procure")) {
            arrayList.clear();
            arrayList.add("procure");
            return arrayList.stream().reduce((a, b) -> a + "" + b).orElse("").toString();
        } else if (arrayList.contains("car")) {
            arrayList.clear();
            arrayList.add("car");
            return arrayList.stream().reduce((a, b) -> a + "" + b).orElse("").toString();
        } else if (arrayList.contains("tendering")) {
            arrayList.clear();
            arrayList.add("tendering");
            return arrayList.stream().reduce((a, b) -> a + "" + b).orElse("").toString();
        } else if (arrayList.contains("price")) {
            arrayList.clear();
            arrayList.add("price");
            return arrayList.stream().reduce((a, b) -> a + "" + b).orElse("").toString();
        } else {
            return arrayList.stream().reduce((a, b) -> a + "" + b).orElse("").toString();
        }
    }

    private String roleListes(JSONArray object) {
        ArrayList arrayList = new ArrayList();
        for (int i = 0; i < object.size(); i++) {
            JSONObject jsonObject = object.getJSONObject(i);
            if (jsonObject.getStr("name").contains("超级管理员")) {
                arrayList.add("vadmin");
                servletContext.setAttribute("roles", "vadmin");
                break;
            }
            if (jsonObject.getStr("name").contains("仓库管理员")) {
                arrayList.add("admins");
                break;
            }
            if (jsonObject.getStr("name").contains("采购")) {
                arrayList.add("procure");
            }
            if (jsonObject.getStr("name").contains("车蚂蚁")) {
                arrayList.add("car");
            }
            if (jsonObject.getStr("name").contains("招投标")) {
                arrayList.add("tendering");
            }
            if (jsonObject.getStr("name").contains("库管员")) {
                arrayList.add("warehouse");
            }

            if (jsonObject.getStr("name").contains("财务")) {
                arrayList.add("price");
            }
        }
        if (arrayList.size() == 0) {
            arrayList.add("default");
        }

        if (arrayList.contains("vadmin")) {
            arrayList.clear();
            arrayList.add("vadmin");
            return arrayList.stream().reduce((a, b) -> a + "" + b).orElse("").toString();
        } else if (arrayList.contains("admins")) {
            arrayList.clear();
            arrayList.add("admins");
            return arrayList.stream().reduce((a, b) -> a + "" + b).orElse("").toString();
        } else {
            return arrayList.stream().reduce((a, b) -> a + "" + b).orElse("").toString();
        }

    }

    //获取城市信息
    public List<CityVo> findCityList() throws Exception {
        String str = HttpUtil.get(Url + "/moving/city/findCityList");
        JSONObject object = JSONUtil.parseObj(str);
        Integer code = (Integer) object.get("code");
        List<CityVo> cityList = new ArrayList<>();
        if (code == 200) {
            Object data = object.get("data");
            JSONObject object1 = JSONUtil.parseObj(data);
            JSONArray data1 = (JSONArray) object1.get("tableData");
            data1.forEach(f -> {
                JSONObject y = (JSONObject) f;
                CityVo cityVo = new CityVo();
                cityVo.setId((Integer) y.get("id"));
                cityVo.setCityName(y.get("name").toString());
                cityList.add(cityVo);
            });
        }
        return cityList;
    }

    // 根据城市获取仓库
    public List<Warehouse> findWarehouseList() throws Exception {
        QueryWrapper wrapper = new QueryWrapper();
        Object roles = servletContext.getAttribute("roles");
        if (roles == null) {
            UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
            wrapper.in("city_id", userInfo.getCityId());
        } else {
            wrapper = null;
        }
        return warehouseService.list(wrapper);
    }

    //数据字典
    public List<Dictionary> findDictionaryList() {
        return dictionaryService.list(new QueryWrapper<Dictionary>().orderByAsc("sort_no"));
    }

    //部门
    public List<Department> findDepartmentList() {
        return departmentService.list();
    }

    //供应商
    public List<SupplierInformation> findSupplierList() {
        return supplierInformationService.list();
    }

    //获取有采购角色的人员
    public List<String> findProcurementRoleList() {
        String str = HttpUtil.get(Url + "/userSystem/user/findUserList?currentPage=1&pageSize=1000&status=true");
        JSONObject object = JSONUtil.parseObj(str);
        String code = object.getStr("code");
        Map<String, Object> map = new HashMap<>();
        List<String> purchaserList = new ArrayList<>();
        if (code.equals("200")) {
            Object data = object.get("data");
            JSONObject object1 = JSONUtil.parseObj(data);
            JSONArray data1 = (JSONArray) object1.get("tableData");
            data1.forEach(f -> {
                JSONObject y = (JSONObject) f;
                if (y.get("name").toString().contains("采购")) {
                    map.put("id", y.get("id").toString());
                    map.put("name", y.get("name"));
                    purchaserList.add(JSONUtil.toJsonStr(map));
                }
            });
        }
        return purchaserList;
    }

}
